package com.cjm.algorithm.leetcode;

import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;

public class Intersect350 {
    public static int[] intersect(int[] nums1, int[] nums2) {
        if (nums1.length < 1 || nums2.length < 1) {
            return new int[0];
        }
        Map<Integer, Integer> map1 = new HashMap<>();
        for (int i = 0; i < nums1.length; i++) {
            Integer integer = map1.get(nums1[i]);
            if (integer != null) {
                map1.put(nums1[i], integer + 1);
            } else {
                map1.put(nums1[i], 1);
            }
        }

        Map<Integer, Integer> map2 = new HashMap<>();
        for (int i = 0; i < nums2.length; i++) {
            Integer integer = map2.get(nums2[i]);
            if (integer != null) {
                map2.put(nums2[i], integer + 1);
            } else {
                map2.put(nums2[i], 1);
            }
        }

        int[] res = new int[nums1.length + nums2.length];
        int index = 0;
        Set<Map.Entry<Integer, Integer>> entries = map2.entrySet();
        for (Map.Entry<Integer, Integer> entry : entries) {
            Integer key = entry.getKey();
            Integer value = entry.getValue();
            Integer integer = map1.get(key);
            if (integer != null) {
                int min = Math.min(value, integer);
                for (int i = 0; i < min; i++) {
                    res[index] = key;
                    index++;
                }
            }
        }
        return Arrays.copyOfRange(res, 0, index);
    }

    public static void main(String[] args) {
        int[] intersect = intersect(new int[]{4,9,5}, new int[]{9,4,9,8,4});
        System.err.println("OK");
    }
}
